package com.lsk.netdisk.auth.authz;

import com.lsk.netdisk.auth.authc.Authc;
import com.lsk.netdisk.auth.mappers.UrlPermissionMapper;
import com.lsk.netdisk.auth.mappers.UserMapper;
import com.lsk.netdisk.auth.model.UrlPermission;
import com.lsk.netdisk.auth.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Authz {
	@Autowired
	private UrlPermissionMapper mapper;
	@Autowired
	private UserMapper userMapper;

	public boolean hasPermission(String url,String token){
		log.info("URL: "+url);
		Permission userPermission = null;
		if (Authc.isUserLogined(token)) {
			User user = Authc.getCurrentUser(token);
			String role = user.getRole();
			userPermission = Permission.valueOf(role);
		}else{
			userPermission = Permission.Guest;
		}
		UrlPermission urlPermission = mapper.queryPermissionByURL(url);
		Permission targetPermission = Permission.valueOf(urlPermission.getRole());
		return userPermission.hasPermission(targetPermission);
	}
	public boolean isAdmin(String token){
		User user = Authc.getCurrentUser(token);
		return user.getRole().equals("Admin");
	}

}
